/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package arraylistdependentqueue;

/**
 *
 * @author mweya
 */
import java.util.ArrayList;
import arraylistdependentqueue.Node;
import arraylistdependentqueue.NoSuchElementException;
public class Queue<AnyType> {
    ArrayList queue = new ArrayList<>();
    
    public Queue() {
        
    }
    
    public Queue(AnyType data) {
        queue.add(new Node<>(data));
    }
    
    
    public boolean offer(AnyType data) {
        try {
            queue.add(new Node<>(data));
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public void add(AnyType data) {
        queue.add(new Node<>(data));
    }
    
    public AnyType peek() {
        if (queue.size() < 1) {
            return (AnyType) null;
        } else {
            Node next = (Node) queue.get(0);
            return (AnyType) (next.getData());
        }
    }
    
    public AnyType element() throws NoSuchElementException {
        if (queue.size() < 1) {
            throw new NoSuchElementException();
        } else {
            Node next = (Node) queue.get(0);
            return (AnyType) (next.getData());
        }
    }
    
    public AnyType poll() {
        if (queue.size() < 1) {
            return (AnyType) null;
        } else {
            Node head = (Node) queue.get(0);
            queue.remove(0);
            return (AnyType) head.getData();
        }
    }
    
    public AnyType remove() throws NoSuchElementException {
        if (queue.size() < 1) {
            throw new NoSuchElementException();
        } else {
            Node head = (Node) queue.get(0);
            queue.remove(0);
            return (AnyType) head.getData();
        }
    }
    
    @Override
    public String toString() {
        int j = 0;
        String out = "Queue:";
        while (j<queue.size()) {
            // The fact that this doesn't work really irritates me:
            // out = out+"\n"+queue.get(j).getData();
            Node node = (Node) queue.get(j);
            out = out+"\n"+node.getData();
            j = j+1;
        }
        return out;
    }
}